﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.ObjectModel;
using System.Collections.Specialized;



namespace TiledShell.Models
{
    public static class TileListManager
    {
        static ObservableCollection<Tile> instance = null;

        public static ObservableCollection<Tile> Tiles
        {
            get
            {
                //This will only happen once.
                if (instance == null)
                {
                    instance = new ObservableCollection<Tile>();
                }
                return instance;
            }
        }  

        private const string FileName = "Tiles.jjp";

        public static void WriteToDisk()
        {
            Stream _stream = File.Open(FileName, FileMode.Create);
            BinaryFormatter _bformateer = new BinaryFormatter();
            _bformateer.Serialize(_stream, Tiles);
            _stream.Close();
        }

        public static void LoadTiles()
        {
            if (File.Exists(FileName))
            {
                Stream _stream = File.Open(FileName, FileMode.Open);
                BinaryFormatter _bformatter = new BinaryFormatter();

                try
                {
                    var temp = (IList<Tile>)_bformatter.Deserialize(_stream);
                    _stream.Close();
                    //Clearing and copying has fewer side-effects than directly replacing
                    //(Don't have to hook up new event handlers and what not).
                    Tiles.Clear();
                    foreach (var item in temp)
                    {
                        Tiles.Add(item);
                    }
                }
                catch (Exception e)
                {
                    //I should do something with exceptions..
                }
                finally
                {
                    _stream.Close();
                }
            }
        }
    }
}
